/*
 * @Author: wuqingchun
 * @Date: 2024-07-12 16:06:43
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-07-12 18:21:45
 */

#include <cstdio>
#include <cstddef>
#include <atomic>
#include <thread>
#include <mutex>
#include <pthread.h>

class CAppSpinLock
{
private:
    /* data */
public:
    CAppSpinLock(/* args */)
    {

    }
    ~CAppSpinLock()
    {

    }

public:
    void lock()
    {
        while (m_bFlag.exchange(true))
        {
            
        }
    }

    void unlock()
    {
        m_bFlag.store(false);
    }

private:
    std::atomic<bool> m_bFlag{false};
};


class CAppWriteFile
{
public:
    CAppWriteFile()
    {
        m_pstFile = fopen("test.txt", "w+");
        if (m_pstFile == nullptr)
        {
            perror("fopen");
        }
    }

    ~CAppWriteFile()
    {

    }

    int32_t Write(const char* pcData, size_t ulLen)
    {
        std::lock_guard<CAppSpinLock> objLG(m_objLock);

        return fwrite(pcData, ulLen, 1, m_pstFile);
    }

private:
    CAppSpinLock m_objLock;
    FILE* m_pstFile = nullptr;
};


int main(int argc, char** argv)
{

    CAppWriteFile objApp;
    
    std::thread t1([&](){
        cpu_set_t stSet = {};
        CPU_ZERO(&stSet);
        CPU_SET(2, &stSet);
        pthread_setaffinity_np(pthread_self(), sizeof(stSet), &stSet);

        while (1)
        {
            objApp.Write("aaaaa", sizeof("aaaaa"));
            printf("1\n");
        }
    });

    std::thread t2([&](){
        cpu_set_t stSet = {};
        CPU_ZERO(&stSet);
        CPU_SET(2, &stSet);
        pthread_setaffinity_np(pthread_self(), sizeof(stSet), &stSet);

        while (1)
        {
            objApp.Write("aaaaa", sizeof("aaaaa"));
            printf("2\n");
        }
    });

    t1.join();
    t2.join();
}